from sqlalchemy import select, desc
from datetime import datetime
from 数据库 import 获取会话, 虎码


文档 = f'''
name: tiger
version: {datetime.today().strftime('%Y-%m-%d')}
sort: original
use_preset_vocabulary: false
columns:
  - text
  - code
...

'''

def 出码():
    with 获取会话() as 会话:
        字典 = {}
        表 = 会话.execute(
            select(虎码)
            # .where(虎码.级别.in_(['1', '2', '3']))
            .order_by(desc(虎码.频数))
        ).scalars()

        一简 = ''
        二简 = ''
        三码 = ''
        四码 = ''
        让全 = ''

        for 行 in 表:
            if 行.容错:
                for 码 in 行.容错.split(','):
                    if len(码) == 3:
                        三码 = ''.join([三码, f'{行.字符}\t{码}\n'])
                    elif len(码) == 4:
                        四码 = ''.join([四码, f'{行.字符}\t{码}\n'])

            if 行.一简:
                一简 = ''.join([一简, f'{行.字符}\t{行.一简}\n'])
                让全 = ''.join([让全, f'{行.字符}\t{行.全码}\n'])

            elif 行.二简:
                二简 = ''.join([二简, f'{行.字符}\t{行.二简}\n'])
                让全 = ''.join([让全, f'{行.字符}\t{行.全码}\n'])
            elif 行.三简:
                三码 = ''.join([三码, f'{行.字符}\t{行.三简}\n'])
                让全 = ''.join([让全, f'{行.字符}\t{行.全码}\n'])
            else:
                if len(行.全码) == 3:
                    三码 = ''.join([三码, f'{行.字符}\t{行.全码}\n'])
                elif len(行.全码) == 4:
                    四码 = ''.join([四码, f'{行.字符}\t{行.全码}\n'])



    with open('./最终成果/tiger.dict.yaml', 'w', encoding='utf-8') as 码表:
        码表.write(文档)
        码表.write(一简)
        码表.write(二简)
        码表.write(三码)
        码表.write(四码)
        码表.write(让全)


    
    with open('./最终成果/tiger.dict.yaml', 'r', encoding='utf-8') as 码表, open('./最终成果/大竹.txt', 'w', encoding='utf-8') as 大竹, open('./最终成果/木易.txt', 'w', encoding='utf-8') as 木易:
        字典 = {}
        for i in range(10):
            码表.readline()
        while 行 := 码表.readline():
            木易.write(行)
            行 = 行.strip().split('\t')
            if 行[1] not in 字典:
                字典[行[1]] = [行[0], ]
            else:
                字典[行[1]].append(行[0])
        for k, v in 字典.items():
            大竹.write(f'{k}\t' + '\t'.join(v) + '\n')


    with open('./最终成果/一二简.txt', 'w', encoding='utf-8') as 一二简, open('./最终成果/四码.txt', 'w', encoding='utf-8') as 四码:
        with 获取会话() as 会话:
            表 = 会话.execute(
                select(虎码)
                .order_by(desc(虎码.频数))
                .limit(3500)
            ).scalars()
            for 行 in 表:
                if 行.一简 or 行.二简:
                    一二简.write(行.字符)
                elif not 行.三简 and len(行.全码) != 3:
                    四码.write(行.字符)


if __name__ == '__main__':
    出码()
